'use strict'
app.controller('TemplateFormController', function($scope, $state, $http, $timeout, time, obj, $stateParams) {

	$scope.api = $scope.serverUrl + "web/template";

    let idStr = $stateParams.id;
    let index = idStr.indexOf("_");
    let id = 0;
    let projectId = undefined;
    if(index > -1){
        let arr = idStr.split("_");
        id = arr[0];
        projectId = arr[1];
    }else{
        id = $stateParams.id;
    }
    // console.log(id)
    
    $scope.query = {
        "size": 10,
        "page": 1,
        "name": ""
    };

    $scope.form = {
        "id": '',
        "name": '',
        "remark": '',
        "content": '',
        "code": '',
        "type": 0,
        "label": '',
        "tplType": 'freemarker',
        "example": "HelloWorld",
        "module": '',
        "suffix": '',
        "nameType": 2,
        "fileType": '',
        "projectId": projectId
    };

    if(projectId != undefined){
        $scope.form.type = 1;
    }

    $scope.nameTypeArr = [
        {id: 0, name: '默认'},
        {id: 1, name: '小驼峰'},
        {id: 2, name: '大驼峰'}
    ];

    $scope.typeArr = [
        {id: 0, name: '公共'},
        {id: 1, name: '私有'},
    ]

    $scope.tplTypeArr = [
        {id: "freemarker", name: 'freemarker'},
        {id: "velocity", name: 'velocity'},
    ]

    $scope.fileTypeArr = [];

    $scope.dialog = {
        "isAdd": true,
        "title": "新增",
    };

    $scope.body = {
        "queryTitle": "查询条件",
        "tableTitle": "数据列表"
    };

    $scope.returnData = {
        recordsTotal: 0,
        recordsFiltered: 0,
        data: []
    };


    let tbl;
    let layer = layui.layer;

    const { createEditor, createToolbar } = window.wangEditor

    const editorConfig = {
        placeholder: 'Type here...',
        onChange(editor) {
            const html = editor.getHtml()
            // console.log('editor content', html)
            const text = editor.getText();
            // console.log('editor content', text)
            $scope.form.content = text;
            $scope.form.code = html;
        }
    }

    const editor = createEditor({
        selector: '#editor-container',
        html: '<p><br></p>',
        config: editorConfig,
        mode: 'default', // or 'simple'
    })

    const toolbarConfig = {}

    const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    })

    $timeout(function(){
        $http.post($scope.serverUrl + "web/sysDictData/list", {dictType: "fileType"}).then(function(res){
            if(res.data.code === 1){
                let arr = res.data.data;
                // console.log(arr)
                for(let i = 0; i < arr.length; i++){
                    $scope.fileTypeArr.push({
                        id: arr[i].label,
                        name: arr[i].value
                    })
                }
                if(arr.length > 0 && id == 0){
                    $scope.form.fileType = arr[0].label;
                    $scope.form.example += "." + $scope.form.fileType
                }
            }else{
                layer.msg(res.data.msg, {icon: 5});
            }
        },
        function(err){
            layer.msg('接口请求异常', {icon: 5});
        });
        if(id != 0){
            $http.get($scope.api + "/" + id).then(function(res){
                    if(res.data.code === 1){
                        let data = res.data.data;
                        obj.copy(data, $scope.form);
                        $scope.nameChange();
                        editor.setHtml($scope.form.code)
                    }else{
                        layer.msg(res.data.msg, {icon: 5});
                    }
                },
                function(err){
                    layer.msg('接口请求异常', {icon: 5});
                });
        }
    }, 0);

    $scope.nameChange = function (){
        let name = "hello_world"
        if($scope.form.nameType === 1){
            name = "helloWorld"
        }else if($scope.form.nameType === 2){
            name = "HelloWorld"
        }
        if($scope.form.prefix != "" && $scope.form.prefix != undefined && $scope.form.prefix != null){
            name = $scope.form.prefix + name;
        }
        if($scope.form.suffix != "" && $scope.form.suffix != undefined && $scope.form.suffix != null){
            name += $scope.form.suffix;
        }
        if($scope.form.fileType != "" && $scope.form.fileType != undefined && $scope.form.fileType != null){
            name += "." + $scope.form.fileType;
        }
        $scope.form.example = name;
    }

    $scope.save = function(){
        let url =  "/";
        if(id == 0){
            $http.post($scope.api + url, $scope.form).then(function(res){
                if(res.data.code === 1){
                    layer.msg('操作成功', {icon: 1});
                    if(projectId != undefined){
                        $state.go("app.projectInfo", {id: projectId + "_1"});
                    }else{
                        $state.go("app.template");
                    }
                }else{
                    layer.msg(res.data.msg, {icon: 5});
                }
            },
            function(err){
                layer.msg('接口请求异常', {icon: 5});
            });
        }else{
            $http.put($scope.api + url, $scope.form).then(function(res){
                if(res.data.code === 1){
                    layer.msg('操作成功', {icon: 1});
                    if(projectId != undefined){
                        $state.go("app.projectInfo", {id: projectId + "_1"});
                    }else{
                        $state.go("app.template");
                    }
                }else{
                    layer.msg(res.data.msg, {icon: 5});
                }
            },
            function(err){
                layer.msg('接口请求异常', {icon: 5});
            });
        }
    };

    $scope.test = function(){
        $http.post($scope.api + "/test", $scope.form).then(function(res){
                if(res.data.code === 1){
                    // window.open($scope.api + "/down/" + res.data.data, "_blank");
                    window.open($scope.api + "/preview/" + res.data.data, "_blank");
                    // download($scope.api + "/down/" + res.data.data, res.data.data);
                }else{
                    layer.msg(res.data.msg, {icon: 5});
                }
            },
            function(err){
                layer.msg('接口请求异常', {icon: 5});
        });
    }

    function download(url, fileName) {
        const a = document.createElement('a');
        a.style.display = 'none';
        a.setAttribute('target', '_blank');
        fileName && a.setAttribute('download', fileName);
        a.href = url;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
});